<template>
  <div class="task common-layout">
    <el-container class="container-box">
      <el-container class="container-content">
        <el-header class="container-header">
          <el-input
            v-model="searchQuery"
            placeholder="搜索任务"
            suffix-icon="el-icon-search"
            clearable
            size="default"
            style="width: 200px; margin-right: 10px"
          >
          </el-input>
          <el-button @click="start" size="default" type="primary"
            >刷新</el-button
          >
        </el-header>
        <el-main class="container-main" v-loading="taskLoading">
          <!-- 表格展示 -->
          <el-table
            class=""
            row-class-name="cursor-pointer"
            :data="taskData"
            @row-click="showTaskRank"
            stripe
            style="width: 100%"
            header-row-class-name="table-header"
          >
            <template v-slot:empty>
              <el-empty
                image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
              />
            </template>
            <el-table-column
              prop="name"
              label="任务"
              sortable
              show-overflow-tooltip
              width=""
            />
            <el-table-column
              prop="type"
              label="类型"
              show-overflow-tooltip
              width="150"
            >
              <template #default="{ row }">
                <el-tag effect="plain" class="question-intable-label">
                  {{ taskTypeInfoCfg[row.type || "question"].title }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="完成条件"
              show-overflow-tooltip
              width=""
            >
              <template #default="{ row }">
                <span>
                  {{
                    taskTypeInfoCfg[row.type || "question"].conditionText(
                      row.questionnum || 0,
                      row.questionac
                    )
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              show-overflow-tooltip
              width="100"
            >
              <template #default="{ row }">
                <el-tag
                  class="container-content-cardItemTag question-intable-label"
                  effect="dark"
                  size="default"
                  :type="checkTaskStatus(row).type"
                >
                  {{ checkTaskStatus(row).title }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="finishCount"
              label="完成人数"
              sortable
              show-overflow-tooltip
              width="120"
            >
              <!-- <template #default="{ row }">
                                <span>
                                    {{ getFinishUser(row.ID, row.questionnum, taskFinishInfo) }}
                                </span>
                            </template> -->
            </el-table-column>
            <el-table-column
              prop=""
              label="开始时间"
              sortable
              show-overflow-tooltip
              width=""
            >
              <template #default="{ row }">
                <span> {{ dayjs(row.starttime).format("YYYY-MM-DD") }} </span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="结束时间"
              sortable
              show-overflow-tooltip
              width=""
            >
              <template #default="{ row }">
                <span> {{ dayjs(row.endtime).format("YYYY-MM-DD") }} </span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            class="pager"
            size="default"
            :page-size="limit"
            :total="totalCount"
            @current-change="changePage"
            layout="total,prev, pager, next"
            :current-page="Math.floor(offset / limit) + 1"
          >
          </el-pagination>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { debounce } from "lodash-es";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncselectteamjobrelations,
  asyncselectteamselectuser,
  asyncteamselectteamjob,
} from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TaskType } from "@/util/type";

const taskTypeInfoCfg: Record<
  TaskType,
  { title: string; conditionText: (num: number, degree?: number) => string }
> = {
  video: {
    title: "观看视频",
    conditionText: (num: number, degree?: number) =>
      `观看${num}节课程视频, 且观看视频时长大于${degree}%`,
  },
  question: {
    title: "题目练习",
    conditionText: (num: number, degree?: number) =>
      `完成${num}题, 且代码题目测试点正确率${degree}%`,
  },
  file: {
    title: "学习资料",
    conditionText: (num: number, degree?: number) => `学习${num}份资料`,
  },
  // 默认
  undefined: {
    title: "任务类型",
    conditionText: (num: number, degree?: number) => `完成条件`,
  },
};
const TaskStatusCfg: {
  [key: number]: {
    title: string;
    type: "primary" | "success" | "info" | "warning" | "danger";
    bntText: string;
    show: boolean;
    disabled: boolean;
  };
} = {
  0: {
    title: "未开始",
    type: "warning",
    bntText: "任务没有开始",
    show: true,
    disabled: true,
  },
  1: {
    title: "已结束",
    type: "info",
    bntText: "任务已经结束",
    show: false,
    disabled: true,
  },
  2: {
    title: "进行中",
    type: "success",
    bntText: "去完成",
    show: true,
    disabled: false,
  },
};

const store = useStore(Storekey);
const route = useRoute();
const router = useRouter();
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});
// 监听团队切换
watch(
  () => teamid.value,
  (o, n) => {
    if (o !== n) start();
  }
);

const teamUsers = ref<Studycodemodel.Iteamuser[]>([]);
// 任务完成情况 userid: 100007, teamjobid: 11048, state: true, count: 2
const taskFinishInfo = ref<Studycodemodel.Iteamjobrelation[]>([]);
// 根据任务id,任务目标数 获取已完成成员
function getFinishUser(
  taskId: number,
  questionnum: number,
  taskFinishInfo: Studycodemodel.Iteamjobrelation[]
) {
  const tmp: string[] = [];
  taskFinishInfo.forEach((e, i) => {
    if (e.teamjobid === taskId && e.count >= questionnum) {
      // 补充name
      const user = teamUsers.value.find((u) => u.userid === e.userid) || {};
      tmp.push(user?.user?.name || "");
    }
  });
  // 已完成 只显示三个 后面是的显示 等X人
  const showCount = 3;
  const n = tmp.length - showCount;
  const str = n > 0 ? `等${n}人` : "";
  return tmp.length;
  return n > 0
    ? [...tmp.splice(0, showCount), `……等${n}人`]
    : [...tmp.splice(0, showCount)];
}
// 我的任务完成情况
function myTaskInfo(row: Studycodemodel.Iteamjob) {
  const questionnum = row.questionnum || 1;
  const n = row.teamjobrelation?.filter((e) => e.userid === user.value?.ID);
  if (n?.length) {
    const _n = n.filter((e) => !e.state);
    const num = Math.floor(
      (n.filter((e) => e.state).length / questionnum) * 100
    );
    return {
      isShow: true,
      num: num > 100 ? 100 : num,
      next: _n,
    };
  }
  return {
    isshow: false,
    num: 0,
  };
}

onMounted(async () => {
  await start();
});
const taskLoading = ref(false);
// 查询条件
const offset = ref<number>(0);
const limit = ref<number>(9999);
// 搜索框的值
const searchQuery = ref("");
// 防抖搜索函数 延迟500ms
const debouncedSearch = debounce(async () => {
  await start();
}, 800);
// 处理输入框变化
watch(searchQuery, () => {
  debouncedSearch();
});
// 具体任务
const questions = ref<Studycodemodel.Iquestion[]>([]);
const courses = ref<Alymodel.IMcourse[]>([]);
const teamFiles = ref<Studycodemodel.Iteamfile[]>([]);
const taskData = ref<Studycodemodel.Iteamjob[]>([]);
const totalCount = ref<number>(0);
async function start() {
  if (!teamid.value) {
    console.log("task index teamid is null");
    return;
  }
  taskLoading.value = true;
  // 任务列表
  await getTeamTask();
  // 团队成员
  teamUsers.value = await asyncselectteamselectuser({ teamid: teamid.value });
  // 完成情况
  const taskID = taskData.value.map((e) => e.ID);
  const ret = await asyncselectteamjobrelations({
    _order: "teamjobid",
    teamid: teamid.value,
    teamjobid: taskID,
    state: true,
  });
  taskFinishInfo.value = ret;
  // 计算完成人数并更新任务数据
  taskData.value = taskData.value.map((task) => {
    const finishCount = getFinishUser(
      task.ID,
      task.questionnum || 1,
      taskFinishInfo.value
    );
    return { ...task, finishCount };
  });
  taskLoading.value = false;
}
async function getTeamTask() {
  let order = ["starttime", "ID"];
  // 任务列表
  const { rows, count, question, course, teamfile } =
    await asyncteamselectteamjob({
      _like: ["name", searchQuery.value],
      _offset: offset.value,
      _limit: limit.value,
      teamid: teamid.value,
      _order: order,
      _sortable: "DESC",
    });
  questions.value = question.map((e) => {
    return { ID: e.ID, name: e.name, label: e.label };
  });
  courses.value = course.map((e) => {
    return { ID: e.ID, name: e.name };
  });
  teamFiles.value = teamfile.map((e) => {
    return { ID: e.ID, name: e.name, size: e.size, url: e.url };
  });
  //
  // 1）任何情况下都优先显示未结束任务，之后才是已结束任务
  // 2）未结束任务 和 已结束任务中，默认根据开始时间排序
  // 3）学生只能看到自己能去完成的任务，老师能看到团队所有的
  taskData.value = rows
    .filter((teamTask) => {
      return (
        user.value?.isAdmin || teamTask.isall || myTaskInfo(teamTask).isShow
      );
    })
    .sort((a, b) => {
      // 获取当前时间
      const currentTime = dayjs().unix();
      // 判断任务状态
      const aIsOngoing = dayjs(a.endtime).unix() >= currentTime; // 是否未结束
      const bIsOngoing = dayjs(b.endtime).unix() >= currentTime; // 是否未结束
      // 优先排序：未结束任务排前面
      if (aIsOngoing !== bIsOngoing) {
        return aIsOngoing ? -1 : 1; // 未结束任务排前面
      }
      // 如果是相同状态的任务（都未结束或都已结束），则根据开始时间排序
      const aStartTime = dayjs(a.starttime).unix();
      const bStartTime = dayjs(b.starttime).unix();
      return aStartTime < bStartTime ? 1 : -1; // 降序排列，开始时间越早排越前
    });
  totalCount.value = count;
}
// formatter
function checkTaskStatus(data: Studycodemodel.Iteamjob) {
  const { starttime, endtime } = data;
  const n = dayjs().unix();
  if (n < dayjs(starttime).unix()) {
    return TaskStatusCfg[0];
  }
  if (n > dayjs(endtime).unix()) {
    return TaskStatusCfg[1];
  }
  return TaskStatusCfg[2];
}
function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
  getTeamTask();
}

async function showTaskRank(teamTask: Studycodemodel.Iteamjob) {
  // 判断是否能够进入详情
  if (user.value?.isAdmin || teamTask.isall || myTaskInfo(teamTask).isShow) {
    // 跳转详情页面
    router.push({ name: "任务详情", params: { ID: teamTask.ID } });
  } else {
    ElMessage.error("没有权限查看此任务详细情况!");
  }
}
</script>

<style scoped>
.container-box {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 7vh;
  --container-bg-color: #fff;
}

.container-header {
  /* margin-top: var(--container-margin); */
  height: var(--container-header-height);
  min-height: var(--container-header-height);
  background: var(--container-bg-color);
  width: 100%;
  padding: var(--container-margin) 11px 0;
  box-shadow: none !important;
}

.container-content {
  background: var(--container-bg-color);
  min-width: 70%;
}

.container-main {
  padding: 0 15px;
  /* !!! */
  overflow: hidden;
}

.pager {
  margin: 10px 0;
  float: right;
}
</style>
